package de.fsujena.chat_pi.client.userInterface;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;

import de.fsujena.chat_pi.client.Client;
import de.fsujena.chat_pi.ressources.message.TextMessage;


public class ConsoleUI implements UserInterface {
	DateFormat df;
	BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
	Client clientObject;


	public ConsoleUI(Client serverObject) {
		df = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );
		this.clientObject = serverObject;
	}

	@Override
	public void postTextMessage(TextMessage msg) {
		String temp="["+msg.getSenderUsername().toUpperCase()+" ("+df.format(msg.getReceived())+")]" + ">> " + msg.getMessageText();
		System.out.println(temp);
		clientObject.msgArray.add(temp);
	}

	@Override
	public void postInfo(String str) {
		System.out.println("[INFO ("+df.format(new Date())+")]" + ">> " + str);
	}

	@Override
	public void postWarning(String str) {
		String temp="[WARNING ("+df.format(new Date())+")]" + ">> " + str;
		System.out.println(temp);
		System.out.println(temp);
		clientObject.msgArray.add(temp);
	}

	@Override
	public void postError(String str) {
		String temp="[ERROR ("+df.format(new Date())+")]" + ">> " + str;
		System.err.println(temp);
		System.out.println(temp);
		clientObject.msgArray.add(temp);
	}
	
	public void postText(String str){
		System.out.println(str);
	}
	
	public void postArray(String str, String[] strArray){
		System.out.printf(str, Arrays.toString(strArray));
		for(int i=0;i<strArray.length;i++){
			clientObject.msgArray.add(strArray[i]);
		}
		clientObject.worker.saveHistory();
	}
	@Override
	public void run() {		
		greeting();
		
		while (true) {
			String cmd = null;
			try {
				cmd = input.readLine();									//read from console
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (cmd.startsWith("$")) {									//checks if input is a command
				clientObject.worker.commander(cmd);				//yes? call commander
			} else if (clientObject.isconnected)
				clientObject.connectionThread.sendTextMessage(cmd);		//no? must be a message so send it to the server (if already connected)
			else
				clientObject.worker.showStatus();						//not connected? show it to the user
		}
	}
	
	
	/**
	 * prints greeting text
	 */
	public void greeting(){
		postText("welcome type $ help to see a list of commands");	//print a greeting
		return;
	}

	@Override
	public void postOwnTextMessage(String str) {
		// do not post own text messages
	}

}
